package com.sinoglobal.wallet.activity;

import java.io.ByteArrayOutputStream;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sinoglobal.wallet.R;
import com.sinoglobal.wallet.api.RemoteImpl;
import com.sinoglobal.wallet.app.SinoValueManager;
import com.sinoglobal.wallet.dialog.LoadingDialog1;
import com.sinoglobal.wallet.entity.W_CouponDetail;
import com.sinoglobal.wallet.task.MyAsyncTask;
import com.sinoglobal.wallet.util.LogUtils;
import com.sinoglobal.wallet.util.NetWorkUtil;
import com.sinoglobal.wallet.util.ScreenUtils;
import com.sinoglobal.wallet.util.TextUtil;

public class W_CouponDetailActivity extends W_ShareAbstractActivity {

	protected Bitmap shareBitmap;
	private boolean isShowProgressDialog=true;
	
	// 核销码
	private TextView tvCouponCode;
	// 使用说明
	private TextView tvCouponInfo;
	private String  SHARE_LINK="";
	private String merchantTelphone="0";
	private String customerTelphone="0";
	private Button btnCall;
	
	private String type;
	private LoadingDialog1 mDialog;
	private String THIRD_PARTY_NAME ;//优惠券来源
	private String COUPON_NAME ;//优惠券名字
	private int USE_STATE ;//优惠券状态
	private String url;//第三方链接
	private View wallet_coupon_info_bottom_layout;
	private LinearLayout wallet_coupon_height_layout;//优惠券布局的高度
	 private  int screenHeight2;
	 private int height;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.wallet_coupon_detail);
		mTemplateRightImg.setImageResource(R.drawable.share);
		  initView();
		   screenHeight2 = ScreenUtils.getScreenHeight(this);
		/*   ViewTreeObserver vto = wallet_coupon_height_layout.getViewTreeObserver(); 
		    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { 
		        public boolean onPreDraw() { 
		           height = wallet_coupon_height_layout.getMeasuredHeight(); 
		         
		            return true; 
		        } 
		    }); */
		 
		
		  int id = getIntent().getIntExtra("COUPON_CLAIM_ID", -1);
           COUPON_NAME = getIntent().getStringExtra("COUPON_NAME");
            THIRD_PARTY_NAME = getIntent().getStringExtra("THIRD_PARTY_NAME");
            USE_STATE = getIntent().getIntExtra("USE_STATE",-1);
           if(COUPON_NAME!=null){
        		mTemplateTitleText.setText(COUPON_NAME);
           }
		// A平台 B商户 C第三方 D商品
		// 初先生坚持不定义常量，我妥协了
		// A 只有文本信息
		// B 信息 核销码 
		// C 信息 外链链接或者链接加核销码
		// D 信息 拨号按钮
		type = getIntent().getStringExtra("COUPON_TYPE");
		LogUtils.v("type======"+type);
		if (type!=null&&type.equals("A")) {
			findViewById(R.id.wallet_coupon).setVisibility(View.GONE);
			tvCouponCode.setVisibility(View.GONE);
			btnCall.setVisibility(View.GONE);
		} else if (type!=null&&type.equals("B")) {
		//	btnCall.setText("拨打商户电话");
			btnCall.setVisibility(View.INVISIBLE);
		} else if (type!=null&&type.equals("C")) {
			findViewById(R.id.wallet_coupon).setVisibility(View.GONE);
			tvCouponCode.setVisibility(View.GONE);
			btnCall.setText("去使用");
		} else if(type!=null&&type.equals("D")) {
			findViewById(R.id.wallet_coupon).setVisibility(View.GONE);
			tvCouponCode.setVisibility(View.GONE);
			btnCall.setText("拨打客服电话");
		}
	/*	String image = getIntent().getStringExtra("LOGO_IMAGE");
		if (TextUtils.isEmpty(image)){
			 Bitmap  bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.wallet_coupon_share_default_img);			
			 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				bitmap.compress(CompressFormat.JPEG, 80, outputStream);
				shareBitmap=compressImageFromByte(outputStream.toByteArray());
		}else
			getBitmapFromNet(image, new BitmapListener() {
				@Override
				public void onResult(Bitmap bitmap) {
					shareBitmap = bitmap;
				}
			});
*/
		 Bitmap  bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.wallet_coupon_share_default_img);			
		 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.JPEG,80, outputStream);
			 shareBitmap=compressImageFromByte(outputStream.toByteArray());
		if (id > 0){
			getData(id);}
		
		/*
		   new Thread(){
				 @Override
				public void run() {
					// TODO Auto-generated method stub
					 LogUtils.v("screenHeight2===="+screenHeight2+"height==="+height);
				}
			  }.start();*/
	}

	private void initView() {
		tvCouponCode = (TextView) findViewById(R.id.wallet_coupon_code);
		tvCouponInfo = (TextView) findViewById(R.id.wallet_coupon_info);
		wallet_coupon_info_bottom_layout = (View) findViewById(R.id.wallet_coupon_info_bottom_layout);
		wallet_coupon_height_layout = (LinearLayout) findViewById(R.id.wallet_coupon_height_layout);
		btnCall = (Button) findViewById(R.id.wallet_call);
		btnCall.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.wallet_right_layout) {
			if(USE_STATE==0){
				if(shareBitmap!=null){
					setWalletShare("我在"+getResources().getString(R.string.w_main_app_name)+"的活动中抢了张"+COUPON_NAME+"，你也快来抢吧!", null, SHARE_LINK+"/?productCode="+ SinoValueManager.getProductID(this), shareBitmap);
				}else{
				showToast("分享数据加载中...");
				
				}
			
			}
		} else if (id == R.id.wallet_call) {
			if(btnCall.getText().equals("去使用")){
				    Bundle bundle = new Bundle();
				    bundle.putString("THIRD_PARTY_NAME", THIRD_PARTY_NAME);
				    bundle.putString("url", url);
				goIntent(W_ActionActivity.class,bundle);
			}else if(btnCall.getText().equals("拨打商户电话")){
			//	showCallPhone(merchantTelphone);
			}else if(btnCall.getText().equals("拨打客服电话")){
				showCallPhone(customerTelphone);
			}else if(id==R.id.wallet_noData){//优惠券
				 if(NetWorkUtil.getNetWorkInfoType(getApplicationContext())==NetWorkUtil.NONE){
						showToast("请检查网络是否连接！");	
						 loadError(true);
						}else{
							loadError(false);;
							getData(id);
						}
			}
			
		}
	}

	private void getData(final int id) {
		MyAsyncTask<W_CouponDetail> task = new MyAsyncTask<W_CouponDetail>(isShowProgressDialog, this, true) {
			@Override
			public W_CouponDetail before(Void... params) throws Exception {
				return RemoteImpl.getInstance().getCouponDetail(id);
			}

			@Override
			public void after(W_CouponDetail result) {
				if (result != null) {
					if (result.getCode().equals("0000")) {
						wallet_coupon_height_layout.setVisibility(View.VISIBLE);
						tvCouponCode.setText(result.getPd().getCOUPON_CODE());
						tvCouponInfo.setText(result.getPd().getUSED_DERECTION());
						SHARE_LINK=result.getPd().getSHARE_LINK();
						//tvCouponCode.setText("1231231231");
					//tvCouponInfo.setText(R.string.coupon_details_shuo);
						merchantTelphone=result.getPd().getSERVICE_TELEPHONE();
						customerTelphone=result.getPd().getSERVICE_TELEPHONE();
						url=result.getPd().getTHIRD_URL();
						if (type!=null&&type.equals("C")) {
							
							if(!TextUtil.stringIsNull(tvCouponCode.getText().toString())){
								findViewById(R.id.wallet_coupon).setVisibility(View.VISIBLE);	
								tvCouponCode.setVisibility(View.VISIBLE);	
							}
						} 
					} else {
						showToast("加载数据失败，请重试");
					}
				}else{
					showToast("加载数据失败，请重试");
				}

			}

			@Override
			public void exception() {
			}
		};
		task.execute();
	}
    /**
     * 弹出拨打电话的dialog
     */
    private void showCallPhone(final String telphone) {
    	if(!merchantTelphone.equals("0")){
    		showDialog(W_CouponDetailActivity.this, "提示", "确定要拨打电话吗？",
					"确定",R.color.w_c14, "取消",R.color.w_c14,true,new DialogOnClickListener() {

				@Override
				public void onSure(View v) {
					  Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + telphone));
	                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	                    startActivity(intent);
				}

				@Override
				public void onCancle(View v) {
				}
			});

    }
    	
    }
	private Bitmap compressImageFromByte(byte[] array) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		newOpts.inJustDecodeBounds = true;// 只读边,不读内容
		Bitmap bitmap = BitmapFactory.decodeByteArray(array, 0, array.length, newOpts);

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		float hh = 95f;//
		float ww = 95f;//
		int be = 1;
		if (w > h && w > ww) {
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置采样率

		newOpts.inPreferredConfig = Config.ARGB_8888;// 该模式是默认的,可不设
		newOpts.inPurgeable = true;// 同时设置才会有效
		newOpts.inInputShareable = true;// 。当系统内存不够时候图片自动被回收

		bitmap = BitmapFactory.decodeByteArray(array, 0, array.length, newOpts);
		return bitmap;
	}

}
